package de.koller.balance.scene.universe;

import Jama.Matrix;
import de.koller.aframe.gl.ATexture;
import de.koller.aframe.gl.ATexture.ITextureBuilder;
import de.koller.aframe.util.math.BasicMatrixOp;
import de.koller.aframe.util.misc.BufferedRandomFloat3D;
import de.koller.aframe.util.misc.ColorGradient;
import de.koller.aframe.util.noise.n2D.Perlin2D;
import de.koller.aframe.util.noise.n3D.ScrollingPerlin3D;
import de.koller.oceanFramework.gl.util.ImagePreview;
import de.koller.oceanFramework.gl.util.ParticleTexture;
import de.koller.oceanFramework.math.RVec3;
import java.util.Random;
import org.lwjgl.opengl.GL11;

public class PlanetTexture extends ATexture implements ITextureBuilder {

	private BufferedRandomFloat3D crnd = new BufferedRandomFloat3D( "./temp/planetRender", new Random() );
	private ScrollingPerlin3D perlin;
	public static final int TEXTURE_SIZE = 2048;
	
	@Override
	protected void setUp( TextureParameters tparam ) {
		tparam.magFilter = GL11.GL_LINEAR;
		tparam.builder = this;
		tparam.size = TEXTURE_SIZE;
	}

	@Override
	public void build( ParticleTexture texture ) {
		perlin = new ScrollingPerlin3D( crnd, 7, .7f );
		float mv = Perlin2D.maxHeight( 0, 7, .7f );
		perlin.normalizeMaxBound( mv );
		
		for( int x = 0; x < texture.getWidth(); x++ ) {
			for( int y = 0; y < texture.getHeight(); y++ ) {
				RVec3 v = new RVec3( 0, 0, 1 );
				Matrix m0 = BasicMatrixOp.createYRotation( 2*Math.PI / texture.getWidth() * (x-texture.getWidth()*.5f) );
				Matrix m1 = BasicMatrixOp.createXRotation( Math.PI / texture.getHeight() * (y-texture.getHeight()*.5f) );
				v = BasicMatrixOp.multiply( v, m0.times( m1 ) );
				v.normalize().mult( 0.49f );
				float mx = v.x + .5f;
				float my = v.y + .5f;
				float mz = v.z + .5f;
				
				float f = perlin.getValue( mx, my, mz );
				int c = ColorGradient.cubic( f, 0xff_ff0000, 0xff_0000ff );
//				if( f > mv * .5f )
//					c = ColorGradient.cubic( (f - .5f) * (1f / .5f), 0xff00ff00, 0xff000000 );
//				else
//					c = ColorGradient.cubic( f * (1f/.5f), 0xff000000, 0xff0000ff );
				
				//c = ColorGradient.cubic( 1f / mv * f, 0xff000000, 0xffffffff );
				texture.setPixel( c, x, y );
			}
			System.out.println( "creating texture: " + x + " / " + texture.getWidth() );
		}
		
		ImagePreview.showRaster( texture, 600, 600 );
		perlin = null;
		crnd = null;
	}
	
	
	
}
